// utils/auth.js

const BASE_URL = 'http://test.uu163yun.com/mapi';
const CHECKED_LOGIN_PATH = '/Live/Tourist/CheckedLogin';

// 与现有登录保持一致的公共头（尽量复用项目现状，避免后端校验失败）
const COMMON_HEADERS = {
  ApiVersion: '6.0', 
  ApiWay: 'API',     
  MerId: 'dc529a26P-aecd-4727-86c4-cb62ad24ab99',
  VendorId: '350'
}

// 校验节流/阈值（毫秒）
const STRICT_CHECK_INTERVAL = 15 * 60 * 1000;  // 受保护操作前，超过则先校验
const SILENT_CHECK_INTERVAL = 30 * 60 * 1000;  // 页面 onShow 静默校验

function nowTsSec() {
  return Math.floor(Date.now() / 1000);
}

function getCachedLogin() {
  return {
    loginResult: wx.getStorageSync('loginResult') || {},
    isLogout: wx.getStorageSync('isLogout') === true,
    lastAuthCheckAt: wx.getStorageSync('lastAuthCheckAt') || 0,
  };
}

function setAuthCheckTime(ts) {
  wx.setStorageSync('lastAuthCheckAt', ts || Date.now());
}

function setLoggedOut() {
  wx.setStorageSync('isLogout', true);
}

function request(url, options = {}) {
  return new Promise((resolve, reject) => {
    wx.request({
      url,
      method: options.method || 'GET',
      header: options.header || {},
      data: options.data || {},
      success: (res) => resolve(res),
      fail: (err) => reject(err),
    });
  });
}

/**
 * 向服务端校验登录态
 * header 需要带：MerId、TimeStamp、UserToken（可选但建议）、VendorId 等
 * 返回 true/false
 */
async function checkLoginWithServer() {
  const { loginResult } = getCachedLogin();
  const userToken = loginResult && loginResult.userToken ? loginResult.userToken : '';
  const headers = {
    ...COMMON_HEADERS,
    TimeStamp: nowTsSec(),
  };
  if (userToken) headers['UserToken'] = userToken;

  try {
    const res = await request(`${BASE_URL}${CHECKED_LOGIN_PATH}`, {
      method: 'POST',
      header: headers,
      data: {}, 
    });

    const ok = res.statusCode === 200 && res.data && res.data.result && res.data.result !== 'NG';
    if (ok) {
      setAuthCheckTime(Date.now());
      // 若服务端校验通过，但本地被标记登出，则撤销登出标记
      wx.setStorageSync('isLogout', false);
      return true;
    }
  } catch (e) {
    // 网络异常不立即清空本地态，交由严格模式下一次再校验
    return false;
  }

  // 服务端明确失败：标记登出
  setLoggedOut();
  return false;
}

/**
 * 确保当前可视为已登录
 * mode = 'strict' | 'silent'
 *  - strict：用于受保护操作，必要时会同步请求阻塞校验
 *  - silent：用于 onShow/onAppShow，必要时后台异步刷新
 * 返回：boolean（是否可继续）
 */
async function ensureLogin({ mode = 'strict' } = {}) {
  const { loginResult, isLogout, lastAuthCheckAt } = getCachedLogin();
  const hasToken = !!(loginResult && loginResult.userToken);

  if (isLogout || !hasToken) {
    return false;
  }

  const now = Date.now();
  if (mode === 'strict') {
    if (now - lastAuthCheckAt > STRICT_CHECK_INTERVAL) {
      const ok = await checkLoginWithServer();
      return !!ok;
    }
    // 足够新：放行，并尝试异步刷新
    checkLoginWithServer();
    return true;
  }

  // silent：仅在需要时后台刷新
  if (now - lastAuthCheckAt > SILENT_CHECK_INTERVAL) {
    // 异步刷新，无需 await
    checkLoginWithServer();
  }
  return true;
}

module.exports = {
  getCachedLogin,
  setAuthCheckTime,
  checkLoginWithServer,
  ensureLogin,
  STRICT_CHECK_INTERVAL,
  SILENT_CHECK_INTERVAL,
};